package com.bingo.mpa.service;

import java.util.LinkedList;

import com.bingo.mpa.dao.AgentDao;
import com.bingo.mpa.dao.PhoneDao;
import com.bingo.mpa.pojo.Agent;
import com.bingo.mpa.pojo.Phone;
import com.bingo.mpa.vo.PhoneObject;

public class PhoneService extends Thread
{
	private static class SingletonHolder
	{
		private static final PhoneService INSTANCE = new PhoneService();
	}

	private PhoneService()
	{
	}

	public static final PhoneService getInstance()
	{
		return SingletonHolder.INSTANCE;
	}

	private boolean running = true;
	private LinkedList<PhoneObject<Phone, String>> queue = new LinkedList<PhoneObject<Phone, String>>();

	public synchronized void close()
	{
		running = false;
		this.notify();
	}

	@Override
	public void run()
	{
		PhoneObject<Phone, String> obj = null;
		Agent agent = null;
		while (running)
		{
			synchronized (this)
			{
				if (this.queue.isEmpty())
				{
					try
					{
						this.wait();
						continue;
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
				else
				{
					obj = queue.poll();
					
					try
					{
						if (obj == null || obj.p == null)
						{
							continue;
						}
						agent = AgentDao.findByName(obj.a);
						if (agent != null)
						{
							obj.p.setAid(agent.getAid());
						}

						Phone tmp = PhoneDao.findByPhone(obj.p.getPhone());
						if (tmp == null)
						{
							PhoneDao.save(obj.p);
						}
						else
						{
							obj.p.setPid(tmp.getPid());
							PhoneDao.update(obj.p);
						}
						Thread.sleep(100);
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			}
			
		}
	}

	public synchronized void add(PhoneObject<Phone, String> obj)
	{
		queue.offer(obj);
		if (!this.isAlive())
		{
			this.start();
		}
		this.notify();
	}
}
